import React, { useState, useEffect, FC, SyntheticEvent, ChangeEvent } from 'react'
import {
  Space, Row, Col, Input,
  Form, Table, Modal, Card, DatePicker
} from 'antd'
import type { Moment } from 'moment'
import type { ColumnsType } from 'antd/es/table'
import XlButtonFC from '@/components/xlbutton/xlbutton'
import XlModalFC from '@/components/xlmodal/xlmodal'
import { Scrollbars } from 'react-custom-scrollbars'
import * as api from '@/api'
import { IData, PagingSize, IResponseCodeType, IFileAttributeAdminModal, IOperateLogModel } from '@/models/common'
import { DownOutlinedIcon } from '@/models/icons'
import util from '@/utils/util'
import './logadmin.scss'
interface ColumnsDataType {
  [name: string]: string
}
export type RangePickerValueType = [Moment | null, Moment | null] | null;
export interface IViewModel {
  rowDetailModalOpen: boolean
  pageLoading: boolean
  /**
   * 表格数据
   */
  logTableList: ColumnsDataType[]
  /**
   * 当前页码
   */
  page: number
  /**
   * 每页数量
   */
  pageSize: number
  /**
   * 是否还有下一页
   */
  hasNextPage: boolean
  querylogName: string
  querylogType: string
  rangePickerValue: RangePickerValueType
  startTime: string
  endTime: string
  logRowDetails: ColumnsDataType
  notAuth: boolean
}

const Index: FC = () => {
  const [data, setData] = useState<IData<IViewModel>>({
    ViewModel: {
      rowDetailModalOpen: false,
      pageLoading: false,
      logTableList: [],
      page: 1,
      pageSize: PagingSize.PageSize,
      hasNextPage: false,
      querylogName: "",
      querylogType: "",
      rangePickerValue: null,
      startTime: '',
      endTime: '',
      logRowDetails: {

      },
      notAuth: false
    }
  })

  useEffect(() => {
    
  }, [])

  const events = {
    //查询
    onClickQuery() {
      const { ViewModel } = data
      ViewModel.page = 1
      methods.requestLogList()
    },
    //查看详情
    onClickLookRow(_: ColumnsDataType, record: ColumnsDataType, index: number) {
      const { ViewModel } = data
      ViewModel.rowDetailModalOpen = true
      ViewModel.logRowDetails = record
      setData({ ...data })
    },
    onLogNameChange(e: ChangeEvent<HTMLInputElement>) {
      const { ViewModel } = data
      ViewModel.querylogName = e.target.value
      setData({ ...data })
    },
    onLogTypeChange(e: ChangeEvent<HTMLInputElement>) {
      const { ViewModel } = data
      ViewModel.querylogType = e.target.value
      setData({ ...data })
    },
    /**
     * @description 自定义日期范围组件改变回调
     * @param {RangePickerValueType} value moment格式的日期值
     * @param {[string, string] | string} dateString 格式化后的日期值
     */
    onRangePickerChange(
      value: RangePickerValueType,
      dateString: [string, string] | string,
    ) {
      // console.log('Selected Time: ', value)
      // console.log('Formatted Selected Time: ', dateString)
      const { ViewModel } = data
      ViewModel.startTime = dateString[0]
      ViewModel.endTime = dateString[1]
      ViewModel.rangePickerValue = value
      setData({ ...data })
    },
    onRowDetailModalCancel() {
      const { ViewModel } = data
      ViewModel.rowDetailModalOpen = false
      setData({ ...data })
    },
    onClickLoadMore() {
      const { ViewModel } = data
      if (ViewModel.hasNextPage) {
        ViewModel.page = ViewModel.page + 1
        ViewModel.pageLoading = true
        setData({ ...data })
        methods.requestLogList()
      }
    },
  }
  const methods = {
    /**
     * 加载日志列表
     */
    async requestLogList() {
      const { ViewModel } = data
      ViewModel.pageLoading = true
      setData({ ...data })
      let { pageSize, logTableList, querylogName, startTime, endTime, querylogType, page } = ViewModel
      let last_log_id: React.Key = ''
      if (logTableList.length) {
        last_log_id = logTableList[logTableList.length - 1].ol_id
      }
      if (page == 1) {
        last_log_id = ''
        logTableList = []
      }
      let query_param = {
        name: querylogName,
        start_time: startTime,
        end_time: endTime,
        operate_type: querylogType,
      }
      let res = await api.common.getOperateLogList<IOperateLogModel>({
        query_param: JSON.stringify(query_param),
        limit: pageSize,
        last_log_id,
        page
      })
      const { code, data: logAdminData, message } = res
      if (code == IResponseCodeType.Success) {
        let { log_list = [] } = logAdminData
        ViewModel.logTableList = [...logTableList, ...log_list]
        if (log_list.length < ViewModel.pageSize) {
          ViewModel.hasNextPage = false
        } else {
          ViewModel.hasNextPage = true
        }
      } else if (code == IResponseCodeType.NotAuth) {
        ViewModel.notAuth = true
      } else {
        util.alertTip(message)
      }
      ViewModel.pageLoading = false
      setData({ ...data })
    },
    createColumns() {
      const columns: ColumnsType<ColumnsDataType> = [
        {
          title: '用户名',
          align: "left",
          key: 'username',
          dataIndex: 'username',
        },
        {
          title: '姓名',
          align: "left",
          key: 'name',
          dataIndex: 'name',
        },
        {
          title: '登录IP',
          align: "left",
          key: 'operate_ip',
          dataIndex: 'operate_ip',
        },
        {
          title: '  时间',
          align: "left",
          key: 'create_at',
          dataIndex: 'create_at',
        },
        {
          title: '日志类型',
          align: "left",
          key: 'operate_type',
          dataIndex: 'operate_type',
        },
        {
          title: '日志详情',
          align: "left",
          key: 'operate_log',
          dataIndex: 'operate_log',
        },
        {
          title: '操作',
          align: "center",
          key: 'action',
          render: (_, record, index) => (
            <Space size={4}>
              <XlButtonFC type='primary' size='small' onClick={() => events.onClickLookRow(_, record, index)}>
                查看详情
              </XlButtonFC>
            </Space>
          ),
        }
      ]
      return columns
    },
    renderPage() {
      if (data.ViewModel.notAuth) {
        return null
      }
      return <>
        <Card title="操作日志">
          <Col className='log-admin-wrap'>
            {/* 按钮操作区域 */}
            <Row align='middle' justify='space-between' className='buttonGroupWrap' gutter={[0, 10]}>
              <Col>
                <Space size={10}>
                  <Input placeholder='用户名' value={data.ViewModel.querylogName} onChange={events.onLogNameChange} allowClear />
                  <Input placeholder='日志类型' value={data.ViewModel.querylogType} onChange={events.onLogTypeChange} allowClear />
                  <DatePicker.RangePicker
                    allowClear
                    onChange={events.onRangePickerChange}
                    value={data.ViewModel.rangePickerValue}
                  />
                  <XlButtonFC type='primary' onClick={events.onClickQuery}>查询</XlButtonFC>
                </Space>
              </Col>
              <Col className='count'>
                {data.ViewModel.hasNextPage ? '已部分加载' : '已全部加载'}，共{data.ViewModel.logTableList.length}个
              </Col>
            </Row>
            {/* 表格区域 */}
            <Row className='tableWrap'>
              <Col className={['tableContent', data.ViewModel.hasNextPage ? 'hasTableContent' : 'noTableContent'].join(" ")}>
                <Table
                  scroll={{
                    x: '100%',
                    y: data.ViewModel.hasNextPage ? 'calc(100vh - 355px)' : 'calc(100vh - 280px)'
                  }}
                  loading={data.ViewModel.pageLoading}
                  tableLayout='fixed'
                  rowKey='ol_id'
                  pagination={false}
                  columns={methods.createColumns()}
                  dataSource={data.ViewModel.logTableList}
                />
              </Col>

              {
                data.ViewModel.hasNextPage ? <Row className='loadmore-wrap' onClick={events.onClickLoadMore}>
                  <Col>点击加载更多</Col>
                  <Row><DownOutlinedIcon className='loadmore-icon' /></Row>
                </Row> : null
              }
            </Row>
          </Col>
        </Card>
        {/* 详情弹出框 */}
        <XlModalFC
          open={data.ViewModel.rowDetailModalOpen}
          footer={null}
          title='详情'
          destroyOnClose
          onCancel={events.onRowDetailModalCancel}
        >
          <Form
            labelCol={{ span: 5 }}
            wrapperCol={{ span: 17 }}
            autoComplete="off"
            disabled
          >
            <Form.Item
              label="用户名"
            >
              <Input value={data.ViewModel.logRowDetails.username} />
            </Form.Item>

            <Form.Item
              label="姓名"
            >
              <Input value={data.ViewModel.logRowDetails.name} />
            </Form.Item>
            <Form.Item
              label="登录IP"
            >
              <Input value={data.ViewModel.logRowDetails.operate_ip} />
            </Form.Item>
            <Form.Item
              label="时间"
            >
              <Input value={data.ViewModel.logRowDetails.create_at} />
            </Form.Item>
            <Form.Item
              label="日志类型"
            >
              <Input value={data.ViewModel.logRowDetails.operate_type} />
            </Form.Item>
            <Form.Item
              label="日志详情"
            >
              <Input.TextArea value={data.ViewModel.logRowDetails.operate_log} />
            </Form.Item>
          </Form>
        </XlModalFC>
      </>
    }
  }
  return methods.renderPage()
}
export default Index
